package structure;

import sort.Sort;

/**
 * 队列
 * 技巧：根据head和tail的关系来判断队列是否为空，或者已满，比较困难，增加一个count用来记录队列中元素的数量，可以比较方便的计算队列的状态。
 */
public class Queue {

    private static int[] queue = new int[10];
    private static int   tail;
    private static int   head;
    private static int   count;

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            add(i);
            Sort.print(queue);
        }
        for (int i = 0; i < 10; i++) {
            remove();
            Sort.print(queue);
        }
    }

    public static void add(int num) {
        if (count >= queue.length) {
            throw new IllegalStateException("队列已满，不能入队！");
        }
        queue[head] = num;
        count++;
        head++;
        if (head >= queue.length) {
            head = 0;
        }
    }

    public static int remove() {
        if (count <= 0) {
            throw new IllegalStateException("队列已空，不能出队！");
        }
        int num = queue[tail];
        queue[tail] = 0;
        count--;
        tail++;
        if (tail >= queue.length) {
            tail = 0;
        }
        return num;
    }

}
